<script>
import dayjs from "dayjs";

export default {
  name: "shopDetail",
  data() {
    return {
      detail: {
        name: "",
        description: "",
        isOpen: true,
        openTime: "",
        address: "",
        carouselList: [],
        intro: "",
      },
      dateList: [],
      selectedDateIndex: 0,
      selectedDate: dayjs().format('YYYY-MM-DD'),
      selectedCount: 0,
      totalPrice: "0.00",
      show: false,
      showNoticePopup: false,
      currentNotice: {},
      minDate: dayjs().format('YYYY-MM-DD'),
      maxDate: dayjs().add(9999, 'year').format('YYYY-MM-DD'),
      ticketList: [],
      selectedTicketId: ''
    };
  },
  watch: {
    selectedDate() {
      this.getTicketList();
    },
    ticketList: {
      handler() {
        this.updateCountAndPrice();
      },
      deep: true
    }
  },
  onLoad({ shopId }) {
    uni.showLoading({
      title: '加载中'
    })
    this.$api.getTicketShopDetail(shopId).then(res => {
      this.detail = {
        ...res,
        carouselList: res.carousel.split(","),
        openTime: `${res.open_start_time} - ${res.open_end_time}`,
        isOpen: this.getOpenStatus(res.open_start_time, res.open_end_time)
      }
      this.getTicketList();
      this.setDateList();
    });
  },
  methods: {
    getSaleCount(item) {
      let key = 'sale_count'
      if (item.virtual_sale_count) {
        key = 'virtual_sale_count'
      }
      return (item[key] > 10000 ? (item[key] / 10000).toFixed(1) + '万+' : item[key] || 0 + '人')
    },
    setDateList(_date = '') {
      let now = _date ? dayjs(_date) : dayjs();
      let dateList = [];
      let _i = 0
      if (!this.detail.isOpen) {
        _i = 1
      }
      for (let i = _i; i < 7; i++) {
        let date = now.add(i, 'day');
        let label = '';
        if (i === 0) label = '今天';
        else if (i === 1) label = '明天';
        else if (i === 2) label = '后天';
        else {
          const weekMap = ['周日','周一','周二','周三','周四','周五','周六'];
          label = weekMap[date.day()];
        }
        dateList.push({
          label,
          date: date.format("YYYY-MM-DD"),
          isToday: i === 0,
        });
      }
      this.dateList = dateList;
      this.selectedDate = this.dateList[this.selectedDateIndex]?.date || '';
    },
    getOpenStatus(openStart, openEnd) {
      let now = new Date().getTime();
      let start = new Date(`${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${openStart}`).getTime();
      let end = new Date(`${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${openEnd}`).getTime();
      return now >= start && now <= end;
    },
    selectDate(idx) {
      this.selectedDateIndex = idx;
      this.selectedDate = this.dateList[idx].date;
    },
    showMoreDate() {
      this.show = true;
    },
    onCalendarConfirm(e) {
      this.show = false;
      let date = e.result;
      this.selectedDateIndex = 0;
      this.selectedDate = date;
      this.setDateList(date);
    },
    onCalendarClose() {
      this.show = false;
    },
    openMap() {
      if (!this.detail.latitude || !this.detail.longitude) {
        uni.showToast({
          title: "无法获取景点位置",
          icon: "none"
        });
        return;
      }
      uni.openLocation({
        latitude: this.detail.latitude,
        longitude: this.detail.longitude,
        name: this.detail.name,
        address: this.detail.address
      });
    },
    getTicketList() {
      if (!this.detail.id) return;
      this.$api.getProductList({
        ticket_shop_id: this.detail.id,
      }).then(res => {
        this.ticketList = ( res || []).map(item => {
          return {
            ...item,
            count: 0
          }
        }).filter(item => !item.parent_id)
      });
    },
    orderTicket() {
      if (!this.$store.state.userInfo.id) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: res => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/index'
              });
            }
          }
        })
        return;
      }
      let list = this.ticketList.filter(item => item.count > 0)
      if (list.length === 0) {
        uni.showToast({
          title: "请选择至少一张票",
          icon: "none"
        });
        return;
      }
      uni.setStorageSync('selectedTicketList', list);
      uni.navigateTo({
        url: "/pages/cart/payment?type=1date=" + this.selectedDate
      })
    },
    showNotice(item) {
      this.currentNotice = item;
      this.showNoticePopup = true;
      console.log('00000');

    },
    addCount(item) {
      item.count++;
      this.updateCountAndPrice();
    },
    subCount(item) {
      if (item.count > 0) {
        item.count--;
        this.updateCountAndPrice();
      }
    },
    updateCountAndPrice() {
      let count = 0;
      let price = 0;
      this.ticketList.forEach(item => {
        count += item.count;
        price += item.count * (parseFloat(item.price) || 0);
      });
      this.selectedCount = count;
      this.totalPrice = price.toFixed(2);
    }
  }
};
</script>

<template>
  <view class="ticket-detail">
    <!-- 轮播图 -->
    <u-swiper
      :list="detail.carouselList"
      height="500"
      class="carousel"
    >
    </u-swiper>

    <!-- 景点信息 -->
    <view class="main-info">
      <view class="title">{{ detail.name }}</view>
      <view class="subtitle">{{ detail.subtitle }}</view>
      <view class="desc">{{ detail.description }}</view>
      <view class="open-status">
        <text class="status" :class="detail.isOpen ? 'open' : 'close'">
          {{ detail.isOpen ? '开园中' : '未开放' }}
        </text>
        <text class="open-time">{{ detail.openTime }}</text>
      </view>
      <view class="address">
        <u-icon name="map-fill" size="28" color="#999" />
        <text>{{ detail.address }}</text>
        <text class="map-btn" @click="openMap">地图</text>
      </view>
    </view>

    <!-- 选日期区块 -->
    <view class="section">
      <view class="section-title">选择日期</view>
      <view class="date-scroll-wrapper">
        <scroll-view scroll-x class="date-scroll">
          <view class="date-row">
            <view
              v-for="(item, idx) in dateList"
              :key="item.date"
              :class="['date-item', (selectedDate ? item.date === selectedDate : idx === selectedDateIndex) ? 'active' : '']"
              @click="selectDate(idx)"
            >
              <view>{{ item.label }}</view>
              <view>{{ item.date }}</view>
            </view>
          </view>
        </scroll-view>
        <view class="more-date" @click="showMoreDate">
          <view>
            <view>更多</view>
            <view>日期</view>
          </view>
          <u-icon name="arrow-right" size="32"></u-icon>
        </view>
        <u-calendar
          v-model="show"
          mode="date"
          :min-date="minDate"
          :max-date="maxDate"
          @change="onCalendarConfirm"
          @close="onCalendarClose"
        />
      </view>
    </view>

    <!-- 门票列表区块 -->
    <view class="section">
      <view class="section-title">门票列表</view>
      <view v-for="item in ticketList" :key="item.id" class="ticket-card" :class="{active: selectedTicketId === item.id}">
        <view class="ticket-info">
          <view class="ticket-name">{{ item.title }}</view>
          <view class="ticket-sale">已售 {{ getSaleCount(item) }} <text class="notice" @click.stop="showNotice(item)">| 预订须知 <u-icon name='arrow-right' size='20'></u-icon></text></view>
        </view>
        <view class="ticket-right">
          <view class="ticket-price">￥{{ item.price }}</view>
          <view class="count-btns">
            <button v-if="item.count === 0" class="plus-btn" @click="addCount(item)">+</button>
            <view v-else class="count-group">
              <button class="minus-btn" @click="subCount(item)">-</button>
              <text class="count-num">{{ item.count }}</text>
              <button class="plus-btn" @click="addCount(item)">+</button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 景点介绍区块 -->
    <view class="section">
      <view class="section-title">景点介绍</view>
      <view class="section-content">
        <u-parse :html="detail.content"></u-parse>
      </view>
    </view>
    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <view class="footer-left">
        <view>已选 {{ selectedCount }}</view>
        <view>合计 <text class="price">￥{{ totalPrice }}</text></view>
      </view>
      <button class="footer-btn" :class="{disabled: selectedCount === 0}" :disabled="selectedCount === 0" @click="orderTicket">立即支付</button>
    </view>

    <!-- 预定须知弹窗 -->
    <u-popup v-model="showNoticePopup" mode="bottom" height="70%" border-radius="24">
      <view class="notice-popup">
        <view class="notice-header">
          <text class="notice-title">预定须知</text>
          <u-icon name="close" size="32" @click="showNoticePopup = false"></u-icon>
        </view>
        <scroll-view scroll-y class="notice-content">
          <u-parse :html="currentNotice.content"></u-parse>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}
.ticket-detail {
  background: #f5f5f5;
  height: 100%;
  overflow: auto;
  padding-bottom: 50rpx;
}
.main-info {
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  margin-top: -40rpx;
  padding: 32rpx;
  overflow: hidden;
  position: relative;
  z-index: 2;
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #222;
  }
  .subtitle {
    color: #6c8cff;
    font-size: 28rpx;
    margin: 8rpx 0;
  }
  .desc {
    color: #999;
    font-size: 26rpx;
    margin-bottom: 8rpx;
  }
  .open-status {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
    .status {
      font-size: 28rpx;
      font-weight: bold;
      margin-right: 16rpx;
      &.open { color: #1ecb8c; }
      &.close { color: #f56c6c; }
    }
    .open-time {
      color: #666;
      font-size: 26rpx;
    }
  }
  .address {
    display: flex;
    align-items: center;
    color: #999;
    font-size: 26rpx;
    .map-btn {
      flex-shrink: 0;
      color: #4e8ef7;
      margin-left: 16rpx;
    }
  }
}
.section {
  background: #fff;
  margin-top: 20rpx;
  padding: 24rpx;
  overflow: hidden;
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 12rpx;
  }
  .section-content {
    color: #333;
    font-size: 26rpx;
    line-height: 1.7;
  }
  .date-scroll-wrapper {
    position: relative;
    width: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .more-date {
      flex-shrink: 0;
      display: flex;
      align-items: center;
      border-radius: 16rpx;
      margin-left: 16rpx;
      text-align: center;
      color: #333;
      font-size: 28rpx;
      border: 2rpx solid transparent;
    }
  }
  .date-scroll {
    flex-grow: 1;
    overflow-x: auto;
  }
  .date-row {
    white-space: nowrap;
    display: inline-block;
    min-width: 100%;
  }
  .date-item {
    display: inline-block;
    vertical-align: top;
    background: #f5f5f5;
    border-radius: 16rpx;
    padding: 16rpx 24rpx;
    margin-right: 16rpx;
    text-align: center;
    color: #333;
    font-size: 28rpx;
    border: 2rpx solid transparent;
  }
  .date-item.active {
    background: #fff0e9;
    color: #f56c6c;
    border-color: #f56c6c;
  }
}
.footer-bar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 24rpx 72rpx 24rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0,0,0,0.03);
  z-index: 10;
  .footer-left {
    font-size: 26rpx;
    color: #333;
    .price {
      color: #f56c6c;
      font-size: 32rpx;
      font-weight: bold;
      margin: 0 8rpx;
    }
    .footer-detail {
      color: #3a7afe;
      margin-left: 12rpx;
      font-size: 24rpx;
    }
  }
  .footer-btn {
    background: #4e8ef7;
    color: #fff;
    font-size: 30rpx;
    border-radius: 32rpx;
    padding: 0 48rpx;
    height: 64rpx;
    line-height: 64rpx;
    font-weight: bold;
    margin: 0;
  }
}
.ticket-card {
  background: #fafafa;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  padding: 32rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  &.active {
    border: 2rpx solid #f56c6c;
    background: #fff0e9;
  }
}
.ticket-info {
  flex: 1;
}
.ticket-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 12rpx;
}
.ticket-sale {
  color: #999;
  font-size: 24rpx;
  .notice {
    color: #3a7afe;
    margin-left: 8rpx;
  }
}
.ticket-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.ticket-price {
  color: #f56c6c;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 16rpx;
}
.count-btns {
  display: flex;
  align-items: center;
  .plus-btn, .minus-btn {
    flex-shrink: 0;
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    background: #f56c6c;
    color: #fff;
    font-size: 32rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 8rpx;
    line-height: 48rpx;
  }
  .minus-btn {
    background: #bbb !important;
  }
  .count-group {
    display: flex;
    align-items: center;
  }
  .count-num {
    min-width: 32rpx;
    text-align: center;
    font-size: 28rpx;
    color: #333;
  }
}
.footer-btn.disabled {
  background: #ccc !important;
  color: #fff !important;
}
.notice-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  .notice-header {
    padding: 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2rpx solid #f5f5f5;
    .notice-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  .notice-content {
    flex: 1;
    padding: 32rpx;
    overflow-y: auto;
  }
}
</style>
